<?php
/**
 +----------------------------------------------------------
 * 4.0大版本升级总脚本
 +----------------------------------------------------------
 * Author: ExBOY
 * Time: 2015-07-03 $
 * [Ecos!] (C)2003-2015 Shopex Inc.
 +----------------------------------------------------------
 */
error_reporting(E_ALL ^ E_NOTICE);

$domain     = $argv[1];
$order_id   = $argv[2];
$host_id    = $argv[3];

if (empty($domain) || empty($order_id) || empty($host_id) )
{
    die('No Params');
}

set_time_limit(0);
require_once(dirname(__FILE__) . '/../../lib/init.php');
cachemgr::init(false);

$db     = kernel::database();

//全局App更新
kernel::single('base_shell_webproxy')->exec_command("update --ignore-download");

echo("\n\nstart step 1....\n\n");

/*第一步*/
/*------------------------------------------------------ */
//-- 批量转换货品为基础物料
/*------------------------------------------------------ */
$suffix    = 'batch_products_material';

$total   = 0;
$succ    = 0;
$fail    = 0;

$page     = 0;#开始页
$limit    = 100;#每次执行数量

$sql    = "SELECT count(*) as nums FROM sdb_ome_products WHERE 1=1 ";
$count  = $db->selectrow($sql);
$total    = $count['nums'];
if(empty($total))
{
    ilog('没有查找到相关货品.', false, $suffix);
    exit;#商品表无数据_全部结束
}
else 
{
    $result    = batch_convert_material();
    
    ilog('第一步,批量货品转基础物料已完成, 共计'.$total.'个，失败'.$fail.'个', true, $suffix);
}

//货品转基础物料方法
function batch_convert_material()
{
    global $db, $page, $limit, $fail, $suffix;
    
    $insert_list    = array();
    $barcode_list   = array();
    $bm_ids         = array();
    
    $field  = 'p.product_id, p.name, p.bn, p.cost, p.price, p.weight, p.unit, p.store, p.store_freeze, p.alert_store, p.barcode, p.visibility, g.serial_number';
    $sql    = "SELECT ". $field ." FROM sdb_ome_products AS p 
               LEFT JOIN sdb_ome_goods AS g ON p.goods_id=g.goods_id 
               WHERE 1=1 LIMIT ". ($page * $limit) .", " . $limit;
    $dataList    = $db->select($sql);
    
    #没有可执行的货品,则退出.
    if(empty($dataList))
    {
        return false;
    }
    
    #拼接数据
    foreach ($dataList as $key => $val)
    {
        $product_id    = $val['product_id'];
        $product_name  = trim($val['name']);
        $product_bn    = $val['bn'];
        $product_bn_crc32    = sprintf('%u', crc32($val['bn']));
        $serial_number       = ($val['serial_number'] == 'true' ? 'true' : 'false');#唯一码
        $visibled            = ($val['visibility'] == 'false' ? 2 : 1);
        
        $cost          = $val['cost'];
        $retail_price  = $val['price'];
        $weight        = $val['weight'];
        $unit          = $val['unit'];
        
        $store         = $val['store'];
        $store_freeze  = $val['store_freeze'];
        $alert_store   = $val['alert_store'];
        
        $insert_list['material'][$product_id]        = "('". $product_id ."','". $product_name ."','". $product_bn ."','". $product_bn_crc32 ."','". $serial_number ."','". $visibled ."','". time() ."')";
        $insert_list['material_ext'][$product_id]    = "('". $product_id ."','". $cost ."','". $retail_price ."','". $weight ."','". $unit ."')";
        $insert_list['material_stock'][$product_id]  = "('". $product_id ."','". $store ."','". $store_freeze ."','". $alert_store ."')";
        
        #条形码
        if($val['barcode'])
        {
            $barcode_list['product_id'][$product_id]    = $product_id;
            $barcode_list['barcode'][$product_id]       = "('". $product_id ."',1,'". $val['barcode'] ."')";
        }
        
        $bm_ids[$product_id]    = $product_id;
    }
    
    #如果货品已存在基础物料中则不处理[注：product_id唯一值]
    $dataList    = array();
    if($bm_ids)
    {
        $sql    = "SELECT bm_id FROM sdb_material_basic_material WHERE bm_id in(". implode(',', $bm_ids) .")";
        $dataList    = $db->select($sql);
    }
    
    if($dataList)
    {
        foreach ($dataList as $key => $val)
        {
            $bm_id    = $val['bm_id'];
        
            if(isset($insert_list['material'][$bm_id]))
            {
                unset($insert_list['material'][$bm_id]);
                unset($insert_list['material_ext'][$bm_id]);
                unset($insert_list['material_stock'][$bm_id]);
                
                unset($bm_ids[$bm_id]);
                
                $fail++;
            }
        }
    }
    
    #插入数据
    if($insert_list['material'])
    {
        #主表
        $insert_sql    = "INSERT INTO `sdb_material_basic_material` (`bm_id`,`material_name`,`material_bn`,`material_bn_crc32`,`serial_number`,`visibled`,`create_time`) VALUES";
        $insert_sql    .= implode(',', $insert_list['material']);
        $result    = $db->exec($insert_sql);
        if($result)
        {
            #扩展表
            $insert_sql    = "INSERT INTO `sdb_material_basic_material_ext` (`bm_id`,`cost`,`retail_price`,`weight`,`unit`) VALUES";
            $insert_sql    .= implode(',', $insert_list['material_ext']);
            $result    = $db->exec($insert_sql);
            if($result)
            {
                #库存表
                $insert_sql    = "INSERT INTO `sdb_material_basic_material_stock` (`bm_id`,`store`,`store_freeze`,`alert_store`) VALUES";
                $insert_sql    .= implode(',', $insert_list['material_stock']);
                $result    = $db->exec($insert_sql);
                if(!$result)
                {
                    ilog('插入库存表出错, 查询起始值:'.($page * $limit), false, $suffix);
                    return false;
                }
            }
            else 
            {
                ilog('插入扩展表出错, 查询起始值:'.($page * $limit), false, $suffix);
                return false;
            }
        }
        else 
        {
            ilog('插入主表出错, 查询起始值:'.($page * $limit), false, $suffix);
            return false;
        }
    }
    
    #转换至销售物料
    if($result)
    {
        $params    = implode(',', $bm_ids);
        $result    = kernel::single('material_basic_exchange')->process($params);
    }
    
    #[判断]条形码是否已存在
    $dataList    = array();
    if($barcode_list['product_id'])
    {
        $sql    = "SELECT bm_id FROM sdb_material_codebase WHERE bm_id in(". implode(',', $barcode_list['product_id']) .")";
        $dataList    = $db->select($sql);
    }
    
    if($dataList)
    {
        foreach ($dataList as $key => $val)
        {
            $bm_id    = $val['bm_id'];
        
            if(isset($barcode_list['barcode'][$bm_id]))
            {
                unset($barcode_list['barcode'][$bm_id]);
                unset($barcode_list['product_id'][$bm_id]);
            }
        }
    }
    
    #[插入]条形码关联基础物料
    if($barcode_list['barcode'])
    {
        $insert_sql    = "INSERT INTO `sdb_material_codebase` (`bm_id`,`type`,`code`) VALUES";
        $insert_sql    .= implode(',', $barcode_list['barcode']);
        $result    = $db->exec($insert_sql);
    }
    
    unset($dataList, $insert_list, $barcode_list);
    
    $page++;
    usleep(1000000);#暂停一秒
    
    #递归调用
    batch_convert_material();
}

echo("start step 2....\n\n");

/*第二步*/
/*------------------------------------------------------ */
//-- 批量转换原有的捆绑商品
/*------------------------------------------------------ */
$suffix    = 'batch_pkg_goods';

$pkg_total   = 0;
$pkg_succ    = 0;
$pkg_fail    = 0;

$pkg_page     = 0;#开始页
$pkg_limit    = 100;#每次执行数量

transPkg();
ilog('第二步,批量转换捆绑商品已完成, 共计'.$pkg_total.'个，成功'.$pkg_succ.'个，失败'.$pkg_fail.'个', true, $suffix);

function transPkg(){
    global $db, $pkg_page, $pkg_limit, $pkg_total, $pkg_succ, $pkg_fail, $suffix;
    
    $pkgObj = app::get('omepkg')->model('pkg_goods');
    $pkgProductObj = app::get('omepkg')->model('pkg_product');
    $salesMaterialObj = &app::get('material')->model('sales_material');
    $salesMaterialExtObj = &app::get('material')->model('sales_material_ext');
    $salesBasicMaterialObj = app::get('material')->model('sales_basic_material');

    $pkgList = $pkgObj->getList('*', array(), ($pkg_page * $pkg_limit), $pkg_limit);
    if($pkgList){
        //合计总共多少个捆绑商品
        $pkg_total += count($pkgList);

        foreach($pkgList as $pkg){
            $old_pkg_key = md5($pkg['pkg_bn']);
            $old_pkg_arr[$old_pkg_key] = $pkg;
            $old_pkg_bns[] = $pkg['pkg_bn'];
        }

        //根据查询出的货号判断是否已被占用，占用的捆绑数据过滤不处理
        $salesMExist = $salesMaterialObj->getList('sales_material_bn', array('sales_material_bn'=>$old_pkg_bns), 0, -1);
        foreach($salesMExist as $exist){
            if(in_array($exist['sales_material_bn'], $old_pkg_bns)){
                //存在就过滤
                $exist_key = md5($exist['sales_material_bn']);
                unset($old_pkg_arr[$exist_key]);
                $pkg_fail++;
                ilog('查询的捆绑商品货号：'.$exist['sales_material_bn'].'已被占用, 查询起始值：'.($pkg_page * $pkg_limit), false, $suffix);
            }
        }

        //剩余的捆绑做转换保存
        foreach($old_pkg_arr as $old_pkg){
            $sales_material_bn_crc32 = sprintf('%u',crc32($old_pkg['pkg_bn']));
            $new_pkg_data = array(
                'shop_id' => '_ALL_',
                'sales_material_name' => $old_pkg['name'],
                'sales_material_bn' => $old_pkg['pkg_bn'],
                'sales_material_bn_crc32' => $sales_material_bn_crc32,
                'sales_material_type' => 2,
                'create_time' => time(),
            );

            $is_save = $salesMaterialObj->save($new_pkg_data);
            if($is_save){
                //保存原来的捆绑货品的扩展信息
                $new_pkg_ext_data = array(
                    'sm_id' => $new_pkg_data['sm_id'],
                    'cost' => 0.00,
                    'retail_price' => 0.00,
                    'weight' => $old_pkg['weight'] ? $old_pkg['weight'] : 0.00,
                    'unit' => '',
                );
                $salesMaterialExtObj->insert($new_pkg_ext_data);

                //获取原来的捆绑商品绑定的货品信息做转换
                $old_pkg_product_arr = $pkgProductObj->getList('*', array('goods_id'=>$old_pkg['goods_id']), 0, -1);
                if($old_pkg_product_arr)
                {
                    if(count($old_pkg_product_arr) > 1)
                    {
                        $pkg_product_list     = array();
                        $pkg_product_count    = 0;
                        foreach ($old_pkg_product_arr as $key => $val)
                        {
                            $pkg_product_list[$val['product_id']]    = array('pkgnum'=>$val['pkgnum'], 'percent'=>0);
                        
                            $pkg_product_count += $val['pkgnum'];
                        }
                    }
                    
                    $percent    = 100;
                    $rate       = 100;#默认
                    $loop       = 1;
                    foreach($old_pkg_product_arr as $old_pkg_product)
                    {
                        $pkg_product_id    = $old_pkg_product['product_id'];
                        
                        #计算贡献占比
                        if($pkg_product_list)
                        {
                            if($loop == count($old_pkg_product_arr))
                            {
                                $pkg_product_list[$pkg_product_id]['percent']    = $percent;
                            }
                            else
                            {
                                $diff_num    = round(($pkg_product_list[$pkg_product_id]['pkgnum']/$pkg_product_count), 2);
                                $diff_num    = intval($diff_num * 10) * 10;
                                $pkg_product_list[$pkg_product_id]['percent']    = $diff_num;
                            
                                $percent    = $percent - $diff_num;
                                $percent    = ($percent < 0 ? 0 : $percent);
                            }
                            $loop++;
                            
                            $rate    = intval($pkg_product_list[$pkg_product_id]['percent']);#取整10的倍数
                        }
                        
                        #插入
                        $addBindData = array(
                            'sm_id' => $new_pkg_data['sm_id'],
                            'bm_id' => $old_pkg_product['product_id'],
                            'number' => $old_pkg_product['pkgnum'],
                            'rate' => $rate,
                        );
                        $salesBasicMaterialObj->insert($addBindData);
                        $addBindData = null;
                    }

                    $salesMaterialObj->update(array('is_bind'=>1),array('sm_id'=>$new_pkg_data['sm_id']));
                }

                $pkg_succ++;
            }else{
                $pkg_fail++;
            }
        }
    }else{
        return false;
    }
    
    #release
    unset($pkgList, $salesMExist, $old_pkg_product_arr);
    
    $pkg_page++;
    usleep(1000000);#暂停一秒
    
    transPkg();
}


/*第三步*/
/*淘宝赠品、crm赠品在原有基础上增加开启关闭状态，默认为关闭，老的设置没用需人工重新设置*/
echo("start step 3....\n\n");

echo("start step 4....\n\n");

/*第四步*/
/*------------------------------------------------------ */
//-- 批量货品冻结库存_转换_基础物料冻结库存
/*------------------------------------------------------ */
$suffix    = 'batch_basic_material_stock';

$total   = 0;
$succ    = 0;
$fail    = 0;

$page     = 0;#开始页
$limit    = 500;#每次执行数量

$sql    = "SELECT count(*) as nums FROM sdb_ome_orders 
           WHERE process_status in('unconfirmed', 'splitting', 'splited', 'is_retrial', 'is_declare') 
           AND status='active' AND ship_status in('0', '2', '3')";
$count  = $db->selectrow($sql);
$total    = $count['nums'];
if(empty($total))
{
    ilog('没有查找到相关订单.', false, $suffix);
}
else 
{
    #首先，设置“基础物料冻结库存”全部为0
    $update_sql    = "UPDATE sdb_material_basic_material_stock SET store_freeze=0 WHERE 1=1";
    $db->exec($update_sql);
    
    #批量转换
    $result    = batch_convert_material_store_freeze();
    
    ilog('第四步,批量基础物料冻结库存已完成, 共计'.$total.'个订单', true, $suffix);
}

/*
 * 未确认、部分拆分的订单对应货品冻结库存转换
*
*/
function batch_convert_material_store_freeze()
{
    global $db, $page, $limit, $suffix;
    
    $sql    = "SELECT o.order_id, i.item_id, i.product_id, i.bn, i.nums, i.sendnum 
               FROM sdb_ome_orders AS o 
               LEFT JOIN sdb_ome_order_items AS i ON o.order_id=i.order_id 
               WHERE o.process_status in('unconfirmed', 'splitting', 'splited', 'is_retrial', 'is_declare')
               AND o.status='active' AND o.ship_status in('0', '2', '3') AND i.nums > i.sendnum 
               LIMIT ". ($page * $limit) .", " . $limit;
    $dataList    = $db->select($sql);
    
    #没有可执行的货品,则退出.
    if(empty($dataList))
    {
        return false;
    }
    
    #拼接数据
    $store_freeze_list    = array();
    $bm_ids    = array();
    
    foreach ($dataList as $key => $val)
    {
        $product_id    = $val['product_id'];
        $nums          = $val['nums'] - $val['sendnum'];#未拆分的订单货品数量
        
        $store_freeze_list[$product_id]    = $store_freeze_list[$product_id] + $nums;
        $bm_ids[$product_id]    = $product_id;
    }
    
    #只更新存在的基础物料冻结库存
    $dataList    = array();
    if($bm_ids)
    {
        $sql    = "SELECT bm_id FROM sdb_material_basic_material_stock WHERE bm_id in(". implode(',', $bm_ids) .")";
        $dataList    = $db->select($sql);
    }
    
    if($dataList)
    {
        foreach ($dataList as $key => $val)
        {
            $bm_id    = $val['bm_id'];
            
            $update_sql    = "UPDATE sdb_material_basic_material_stock
                              SET store_freeze=store_freeze+". intval($store_freeze_list[$bm_id]) ."
                              WHERE bm_id=". $bm_id;
            $db->exec($update_sql);
        }
    }
    
    #release
    unset($dataList, $store_freeze_list, $bm_ids);
    
    $page++;
    usleep(1000000);#暂停一秒
    
    #递归调用
    batch_convert_material_store_freeze();
}

echo("start step 5....\n\n");

/*第五步*/
/*------------------------------------------------------ */
//-- 批量转换订单、订单对象表、订单商品表
/*------------------------------------------------------ */
$suffix    = 'batch_orders_material';

$total   = 0;
$succ    = 0;
$fail    = 0;

$page     = 0;#开始页
$limit    = 500;#每次执行数量

$sql    = "SELECT count(*) as nums FROM sdb_ome_orders WHERE 1=1 ";
$count  = $db->selectrow($sql);
$total    = $count['nums'];
if(empty($total))
{
    ilog('没有查找到订单.', false, $suffix);
}
else 
{
    $result    = batch_convert_orders();
    
    ilog('第五步,批量转换订单明细已完成, 共计'.$total.'个，失败'.$fail.'个', true, $suffix);
}

/*
 * 订单明细批量转换方法
*
*/
function batch_convert_orders()
{
    global $db, $page, $limit, $fail, $suffix;

    $omeOrderObjectsObj = &app::get('ome')->model('order_objects');#订单对象表
    $omeOrderItemsObj = &app::get('ome')->model('order_items');#订单商品表
    $salesMaterialShopFreezeObj = &app::get('material')->model('sales_material_shop_freeze');#销售物料店铺冻结

    #查询订单
    $sql    = "SELECT
               a.order_id, a.order_bn, a.archive, a.status, a.process_status, a.pay_status, a.ship_status, a.shop_id, a.is_fail, 
               b.obj_id, b.obj_type, b.goods_id, b.bn, b.quantity
               FROM sdb_ome_orders AS a
               LEFT JOIN sdb_ome_order_objects AS b ON a.order_id=b.order_id
               WHERE 1=1
               LIMIT ". ($page * $limit) .", " . $limit;
    $orderList    = $db->select($sql);
    
    #没有可执行的货品,则退出.
    if(empty($orderList))
    {
        return false;
    }
    
    foreach ($orderList as $key => $val)
    {
        #订单状态
        $order_archive     = $val['archive'];
        $order_status      = $val['status'];
        $process_status    = $val['process_status'];
        $pay_status    = $val['pay_status'];
        $ship_status    = $val['ship_status'];
        
        $new_object    = array();
        $new_item      = array();
        
        #获取订单货品bn对应销售物料
        $get_sales_material    = get_sales_material($val['bn']);
        if(empty($get_sales_material))
        {
            #失败订单_未匹配到销售物料
            if($val['is_fail'] == 'true' && $order_status == 'active')
            {
                #更新objects表中goods_id=0
                $new_object['obj_id']      = $val['obj_id'];
                $new_object['goods_id']    = 0;
                $omeOrderObjectsObj->save($new_object);
                
                #删除关联items表中记录
                $omeOrderItemsObj->delete(array('order_id'=>$val['order_id'], 'obj_id'=>$val['obj_id']));
            }
            
            ilog('订单号：'. $val['order_bn'] .', 未找到商品BN：'.$val['bn'], false, $suffix.'_notbn');
            
            $fail++;
            continue;
        }
        
        #第一种：失败订单
        if($val['is_fail'] == 'true' && $order_status == 'active')
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']      = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
            
            $is_save    = $omeOrderObjectsObj->save($new_object);
            
            #2.销售物料店铺冻结
            if($is_save)
            {
                $is_freeze    = set_sales_material_shop_freeze($get_sales_material['sm_id'], $val['shop_id'], $val['quantity']);
            }
        }
        #第二种：未确认订单
        elseif(in_array($process_status, array('unconfirmed', 'is_retrial', 'is_declare')) && $order_archive == 0 && $order_status == 'active')
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']     = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
            
            $is_save    = $omeOrderObjectsObj->save($new_object);
            
            #2.销售物料店铺冻结
            if($is_save)
            {
                $is_freeze    = set_sales_material_shop_freeze($get_sales_material['sm_id'], $val['shop_id'], $val['quantity']);
            }
        }
        #第三种：已拆分完_已发货
        elseif($process_status == 'splited' && $ship_status == '1')
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']     = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
            
            $is_save    = $omeOrderObjectsObj->save($new_object);
        }
        #第四种a：已拆分完_部分发货
        elseif($process_status == 'splited' && $ship_status == '2')
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']     = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
            
            $is_save    = $omeOrderObjectsObj->save($new_object);
        }
        #第四种b：已拆分完_未发货
        elseif($process_status == 'splited' && $ship_status == '0')
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']     = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
        
            $is_save    = $omeOrderObjectsObj->save($new_object);
        }
        #第五种：部分拆分_部分发货
        elseif($process_status == 'splitting' && $ship_status == '2' && $order_archive == 0 && $order_status == 'active')
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']     = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
            
            $is_save    = $omeOrderObjectsObj->save($new_object);
            
            #2.计算未拆分的订单商品数量
            $quantity    = get_order_object_quantity($val['obj_id']);
            
            #3.销售物料店铺冻结
            if($is_save)
            {
                $is_freeze    = set_sales_material_shop_freeze($get_sales_material['sm_id'], $val['shop_id'], $quantity);
            }
        }
        #第六种：部分拆分_未发货
        elseif($process_status == 'splitting' && $ship_status == '0' && $order_archive == 0 && $order_status == 'active')
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']     = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
            
            $is_save    = $omeOrderObjectsObj->save($new_object);
            
            #2.计算未拆分的订单商品数量
            $quantity    = get_order_object_quantity($val['obj_id']);
            
            #3.销售物料店铺冻结
            if($is_save)
            {
                $is_freeze    = set_sales_material_shop_freeze($get_sales_material['sm_id'], $val['shop_id'], $quantity);
            }
        }
        #第七种：已取消
        elseif($process_status == 'cancel')
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']     = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
        
            $is_save    = $omeOrderObjectsObj->save($new_object);
        }
        #第八种：其它情况[余单撤消]
        else
        {
            #1.转换objects对象对应的销售物料
            $new_object['obj_id']     = $val['obj_id'];
            $new_object['goods_id']    = $get_sales_material['sm_id'];
            $new_object['bn']          = $get_sales_material['sales_material_bn'];
            $new_object['name']        = $get_sales_material['sales_material_name'];
        
            $is_save    = $omeOrderObjectsObj->save($new_object);
        }
        
        #release
        unset($get_sales_material, $new_object);
    }
    
    #release
    unset($orderList, $omeOrderObjectsObj, $omeOrderItemsObj, $salesMaterialShopFreezeObj, $sql);
    
    $page++;
    usleep(1000000);#暂停一秒
    
    #递归调用
    batch_convert_orders();
}


/*第六步*/
/*------------------------------------------------------ */
//-- 检验库存深度中店铺货品是否存在于销售物料列表中,不存在则解绑
/*------------------------------------------------------ */
$suffix    = 'batch_convert_mapping_inventorydepth';

$total   = 0;
$succ    = 0;
$fail    = 0;

$page     = 0;#开始页
$limit    = 100;#每次执行数量

$sql    = "SELECT count(*) as nums FROM sdb_inventorydepth_shop_skus WHERE mapping='1'";
$count  = $db->selectrow($sql);
$total    = $count['nums'];

if(empty($total))
{
    ilog('没有查找到已绑定的店铺货品.', false, $suffix);
}
else
{
    $result    = batch_convert_mapping_inventorydepth();
    
    ilog('第六步,批量库存深度中店铺货品检验绑定已完成, 共计'.$total.'个店铺货品已绑定', true, $suffix);
}

/*
 * 库存深度中店铺货品与销售物料匹配
*
*/
function batch_convert_mapping_inventorydepth()
{
    global $db, $page, $limit;
    
    $sql    = "SELECT id, shop_id, shop_product_bn, bind
               FROM sdb_inventorydepth_shop_skus WHERE mapping='1'
               LIMIT ". ($page * $limit) .", " . $limit;
    $dataList    = $db->select($sql);
    
    #没有可执行的货品,则退出.
    if(empty($dataList))
    {
        return false;
    }
    
    foreach ($dataList as $key => $val)
    {
        $shop_id            = $val['shop_id'];
        $shop_product_bn    = $val['shop_product_bn'];
    
        $sql    = "SELECT sm_id, sales_material_bn, sales_material_type
                   FROM sdb_material_sales_material WHERE sales_material_bn='". $shop_product_bn ."'
                   AND is_bind=1 AND shop_id in('_ALL_', '". $shop_id ."')";
        $row    = $db->selectrow($sql);
    
        #更新
        if($row)
        {
            #绑定
            $bind    = ($row['sales_material_type'] == 2 ? '1' : '0');#是否捆绑商品
            $update_sql    = "UPDATE sdb_inventorydepth_shop_skus SET mapping='1', bind='". $bind ."' WHERE id='". $val['id'] ."'";
        }
        else
        {
            #取消绑定
            $update_sql    = "UPDATE sdb_inventorydepth_shop_skus SET mapping='0', bind='0', update_time='". time() ."' WHERE id='". $val['id'] ."'";
        }
        $db->exec($update_sql);
    }
    
    #release
    unset($dataList, $row, $sql, $update_sql);
    
    $page++;
    usleep(1000000);#暂停一秒
    
    #递归调用
    batch_convert_mapping_inventorydepth();
}

echo("...END...\n\n");

/**
 * 根据bn查找对应销售物料
 * @$bn string 货号
 * return Array
 */
function get_sales_material($bn)
{
    global $db;

    if(empty($bn))
    {
        return false;
    }

    $sql    = "SELECT sm_id, sales_material_name, sales_material_bn, sales_material_type
               FROM sdb_material_sales_material WHERE sales_material_bn='". $bn ."' AND is_bind=1";
    $row    = $db->selectrow($sql);

    #release
    unset($sql);
    
    return $row;
}

/**
 * 更新销售物料店铺冻结
 * @$bn string 货号
 * return Array
 * $salesMShopFreezeLib->freeze($shop_id, $sm_id, $quantity);
 */
function set_sales_material_shop_freeze($sm_id, $shop_id, $quantity)
{
    global $db;

    $quantity    = intval($quantity);
    if(empty($shop_id) || empty($sm_id) || empty($quantity))
    {
        return false;
    }

    $sql    = "SELECT * FROM sdb_material_sales_material_shop_freeze WHERE sm_id='". $sm_id ."' AND shop_id='". $shop_id ."'";
    $row    = $db->selectrow($sql);

    if($row)
    {
        $sql    = "UPDATE sdb_material_sales_material_shop_freeze SET shop_freeze=shop_freeze + ". $quantity ."
                   WHERE sm_id='". $sm_id ."' AND shop_id='". $shop_id ."'";
    }
    else
    {
        $sql    = "INSERT INTO `sdb_material_sales_material_shop_freeze` (`sm_id`,`shop_id`,`shop_freeze`)
                   VALUES('". $sm_id ."','". $shop_id ."','". $quantity ."')";
    }
    $db->exec($sql);
    
    #release
    unset($row, $sql);

    return true;
}

/**
 * 查询订单中未拆分的商品数量
 * @$object_id intval 对象id
 * return $num
 */
function get_order_object_quantity($obj_id)
{
    global $db;
    
    if(empty($obj_id))
    {
        return 0;#防止没有订单明细
    }
    
    #订单明细
    $sql    = "SELECT j.obj_id, j.obj_type, j.quantity, i.item_id, i.product_id, i.nums, i.sendnum FROM sdb_ome_order_objects AS j 
               LEFT JOIN sdb_ome_order_items AS i ON j.obj_id=i.obj_id 
               WHERE j.obj_id=". $obj_id ." AND i.delete='false'";
    $row    = $db->selectrow($sql);
    
    if(empty($row))
    {
        return 0;#明细已全部删除,则跳出
    }
    
    #已拆分审核的数量
    $sql = "SELECT SUM(number) AS 'num' FROM `sdb_ome_delivery_items_detail` did 
            JOIN `sdb_ome_delivery` d ON d.delivery_id=did.delivery_id 
            WHERE did.order_item_id='". $row['item_id'] ."' AND did.product_id='". $row['product_id'] ."' 
            AND d.status != 'back' AND d.status != 'cancel' AND d.status!='return_back' AND d.is_bind = 'false'";
    $oi = $db->selectrow($sql);
    
    $left_nums    = $row['nums'] - intval($oi['num']);
    if ($row['obj_type'] == 'pkg' || $row['obj_type'] == 'giftpackage')
    {
        $left_nums    = intval($row['quantity'] / $row['nums'] * $left_nums);
    }
    
    #release
    unset($row, $oi, $sql);
    
    return $left_nums;#返回剩余未拆分的数量
}


/**
 * 日志
 */
function ilog($str, $flag = false, $suffix='')
{
    global $domain;
    
    $suffix    = ($suffix ? $suffix . '_' : '');#文件后缀名
    
    $filename = dirname(__FILE__) . '/../logs/upgrade4.0_'. $suffix .'fail_' . date('Y-m-d') . '.log';
    
    if($flag)
    {
        $filename = dirname(__FILE__) . '/../logs/upgrade4.0_'. $suffix .'success_' . date('Y-m-d') . '.log';
    }
    
    $fp = fopen($filename, 'a');
    fwrite($fp, date("m-d H:i") . "\t" . $domain . "\t" . $str . "\n");
    fclose($fp);
}
